package com.ruoyi.project.mahjong.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.PoolDto;
import com.ruoyi.project.mahjong.domain.enu.MathDeskState;
import com.ruoyi.project.mahjong.domain.enu.PersonState;
import com.ruoyi.project.mahjong.domain.enu.TablenumberState;
import com.ruoyi.project.mahjong.domain.vo.AutoMateVo;
import com.ruoyi.project.mahjong.domain.vo.MoRenVo;
import com.ruoyi.project.mahjong.mapper.TablePoolMapper;
import com.ruoyi.project.mahjong.service.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 陪桌数据池Controller
 *
 * @author ruoyi
 * @date 2023-07-25
 */
@RestController
@RequestMapping("/mahjong/pool")
public class TablePoolController extends BaseController {
    @Autowired
    private ITablePoolService tablePoolService;
    @Autowired
    private ITReservationService tReservationService;
    @Autowired
    private IDeskMemberService deskMemberService;

    @Autowired
    private ITMemberService tMemberService;

    @Autowired
    private IDeskIngService deskIngService;

    @Autowired
    private TablePoolMapper tablePoolMapper;

    @Autowired
    private ITTablenumberService tTablenumberService;

    /**
     * 查询陪桌数据池列表
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:list')")
    @GetMapping("/list")
    public TableDataInfo list(TablePool tablePool) {
        startPage();
        tablePool.setIsStart("0");
        List<TablePool> list = tablePoolService.selectTablePoolList(tablePool);
        return getDataTable(list);
    }

    @GetMapping("/myselectdetails")
    public AjaxResult myselectdetails(PoolDto dto) {
        Long tableNumber = tablePoolService.selectAutoMate(dto);
//        MoRenVo moRenVo = new MoRenVo();
//        moRenVo.setCount("2");
//        moRenVo.setSource("0");
//        moRenVo.setMode("common");
//        moRenVo.setDeskId(tableNumber);
//        System.out.println(moRenVo);
        return AjaxResult.success(tableNumber);
    }

    /**
     * 预约信息加载到当前配桌池
     *
     * @return
     */
    @GetMapping("/loadupdatePool")
    public AjaxResult loadupdatePool() {
        tReservationService.loadupdatePool();
        return AjaxResult.success();
    }

    /**
     * 查看拼桌详情
     *
     * @param dto
     * @return
     */
    @GetMapping("/selectdetails")
    public AjaxResult selectdetails(PoolDto dto) {
        Map<String, Object> result = tablePoolService.selectdetails(dto);
        if (result.containsKey("desk")){
            DeskIng desk = (DeskIng) result.get("desk");
            desk.setSource("0");
            desk.setCount("2");
            desk.setMode("common");
            desk.setIntegral("1/2");
            result.put("desk",desk);
        }

        return AjaxResult.success(result);
    }
    @GetMapping("/selectdetails2")
    public AjaxResult selectdetails2(PoolDto dto) {

        return AjaxResult.success(tablePoolService.selectAutoMate(dto));
    }

    /**
     * 进行人员陪桌
     *
     * @param dto
     * @return
     */
    @GetMapping("/match")
    public AjaxResult match(PoolDto dto) {
        tablePoolService.match(dto);
        return AjaxResult.success();
    }

    /**
     * 配桌
     *
     * @param dto
     * @return
     */
    @GetMapping("/chengju")
    public AjaxResult chengju(PoolDto dto) {
        tablePoolService.chengju(dto);
        return AjaxResult.success();
    }

    /**
     * 导出陪桌数据池列表
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:export')")
    @Log(title = "陪桌数据池", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TablePool tablePool) {
        List<TablePool> list = tablePoolService.selectTablePoolList(tablePool);
        ExcelUtil<TablePool> util = new ExcelUtil<TablePool>(TablePool.class);
        return util.exportExcel(list, "pool");
    }

    /**
     * 获取陪桌数据池详细信息
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tablePoolService.selectTablePoolById(id));
    }

    /**
     * 新增陪桌数据池
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:add')")
    @Log(title = "陪桌数据池", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TablePool tablePool) {
       /* DeskMember member=new DeskMember();
        member.setDeskId(tablePool.getDeskNumber());
        List<DeskMember> deskMemberList=deskMemberService.selectDeskMemberList(member);
        if(ObjectUtil.isNotEmpty(deskMemberList)){
            if(deskMemberList.size()>3){
                return AjaxResult.error("该桌人员已满，不允许添加!");
            }
        }*/
        int check = tablePoolService.checkMember(tablePool);
        if (check == 0) {
            try {
                return toAjax(tablePoolService.insertTablePool(tablePool));
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());

            }
        } else {
            return AjaxResult.error("该用户已存在不用重复添加!");
        }
    }

    /**
     * 修改陪桌数据池
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:edit')")
    @Log(title = "陪桌数据池", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TablePool tablePool) {
       /* TablePool checkPool=tablePoolService.selectTablePoolById(tablePool.getId());
        if(checkPool.getState().equals(MyConstat.START)){
            TMember member=tMemberService.selectTMemberById(tablePool.getMemberId());
            return AjaxResult.error(member.getName()+"已，不允许修改！");
        }*/

        try {
            return toAjax(tablePoolService.updateTablePool(tablePool));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除陪桌数据池
     */
    @PreAuthorize("@ss.hasPermi('mahjong:pool:remove')")
    @Log(title = "陪桌数据池", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            TablePool pool = tablePoolService.selectTablePoolById(id);
            if ((MyConstat.START).equals(pool.getState())) {
                TMember member = tMemberService.selectTMemberById(pool.getMemberId());
                return AjaxResult.error(member.getName() + "已开桌，不允许删除！");
            }
        }

        return toAjax(tablePoolService.deleteTablePoolByIds(ids));
    }

    @GetMapping("/topchengju/{ids}")
    public AjaxResult topchengju(@PathVariable Long[] ids) { //检查数据
        if (ids.length != 4) {
            return AjaxResult.error("人数不够不允许成局！");
        }
        List<Long> deskList = new ArrayList<>();
        Long  deskId=null;
        for (Long id : ids) {
            TablePool pool = tablePoolService.selectTablePoolById(id);
            deskId=pool.getDeskNumber();
            deskList.add(pool.getDeskNumber());
            if (!(MyConstat.START).equals(pool.getState())) {
                TMember member = tMemberService.selectTMemberById(pool.getMemberId());
                return AjaxResult.error(member.getName() + "没有排桌不允许成局！");
            }
        }
        HashSet<Long> set = new HashSet<>(deskList);
        if (set.size() != 1) {
            return AjaxResult.error("桌号不一致不允许成局！");
        }
        //更新数据
        for (Long id : ids) {
            TablePool pool = new TablePool();
            pool.setStatus(MyConstat.START);
            pool.setId(id);
            pool.setState(MyConstat.PZ);
            tablePoolMapper.updateTablePool(pool);
        }


        TTablenumber tTablenumber = tTablenumberService.selectTTablenumberById(deskId);

        DeskIng ing = new DeskIng();
        ing.setDeskId(deskId);
        //设置为进行中
        ing.setBak2(MyConstat.DESK_ING);
        if (tTablenumber.getStatus().equals(TablenumberState.NO_LOCK.getValue())) {
            ing.setStatus(MathDeskState.DP.getValue());
            ing.setBak2(MyConstat.DESK_ING);
            deskIngService.insertDeskIng(ing);
            tTablenumber.setStatus(TablenumberState.LOCK.getValue());
            tTablenumberService.updateTTablenumber(tTablenumber);
        } else {
            List<DeskIng> deskIngList = deskIngService.selectDeskIngList(ing);
            ing=deskIngList.get(0);
        }
        TablePool pool = new TablePool();
        pool.setDeskNumber(ing.getDeskId());
        if(!ing.getStatus().equals(MathDeskState.DP.getValue())){
            return AjaxResult.error("该桌已经排，不用重复操作！");
        }
        ing.setStatus(MathDeskState.CJ.getValue());
        ing.setBak2(MyConstat.DESK_ING);
        deskIngService.updateDeskIng(ing);
        for (Long id : ids) {
            TablePool mypool = tablePoolService.selectTablePoolById(id);
            DeskMember deskMember = new DeskMember();
            deskMember.setMemberId(mypool.getMemberId());
            deskMember.setMemberName(tMemberService.selectTMemberById(mypool.getMemberId()).getName());
            deskMember.setDeskId(ing.getId());
            deskMember.setState(PersonState.AP.getValue());
            deskMemberService.insertDeskMember(deskMember);
        }
        return AjaxResult.success();

    }
}
